"""
解析srt文件
"""
import http.client
import hashlib
import re
import urllib
import random
import json
import time

appid = '20151210000007618'  
secretKey = 'Ul0O_5kCziSFxmPAeWD7'  

fromLang = 'auto'   #原文语种
toLang = 'zh'   #译文语种


class Srt(object):
    
    def __init__(self,srt_path=''):
        super(Srt,self).__init__()
        
        self.__raw_data,self.__data_list = self.__read_srt(srt_path)



    def __read_srt(sekf,srt_path):
        raw_data = ''
        data = []
    
        with open(srt_path,'r',encoding='utf8') as r:
            raw_data = r.read()
        with open(srt_path,'r',encoding='utf8') as r:
            data = r.readlines()
        # data_list = [ i for i in data if i !='\n']
        # data_list = data.split('\n')
        return raw_data,data

    def data_list(self):
        """
        原始字幕直接行格式
        """
        return self.__data_list

    def _get_pure_data(self):
        _data = {}
        if self.__data_list:
            row_line_list = [f'{i+1}\n' for i in range(self.rows())]
            row_line_list.append('\n')
            for i in range(len(self.__data_list)):
                d = self.__data_list[i]
                if d not in row_line_list and  '-->' not in d :
                    _data[i] = d 
        return _data

    def raw_data(self):
        return self.__raw_data

    def rows(self):
        """
        获取行数
        """
        last_row = self.__data_list[-4]
        return int(last_row.replace('\n',''))

    # def _get_pure_data(self):
    #     """
    #     获取干净的数据
    #     """
    #     pure_data = []
    #     if self.__data_list:
    #         row_line_list = [f'{i+1}\n' for i in range(self.rows())]
    #         for d in self.__data_list:
    #             if d not in row_line_list and  '-->' in d:
    #                 pure_data.append(d)
    #     return pure_data



    def get_clip_count(self):
        """
        获取每次翻译的真实行数
        """
        clip_count = 0
        pure_data = self._get_pure_data()
        if pure_data:
            # keys = sorted(list(pure_data.keys()))
            # vs = [pure_data[i] for i in keys]
            vs = pure_data.values()
            per_number_list = [len(i) for i in vs]
            max_per_number = max(per_number_list)
            # print('max_per_number:',max_per_number)
            clip_count = 1950//max_per_number

        return clip_count




    def translate(self,quer):
        data_list=[]
        myurl = '/api/trans/vip/translate'
        salt = random.randint(32768, 65536)
        sign = appid + quer + str(salt) + secretKey
        sign = hashlib.md5(sign.encode()).hexdigest()
        myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(quer) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
        salt) + '&sign=' + sign
        try:
            httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
            httpClient.request('GET', myurl)
            # response是HTTPResponse对象
            response = httpClient.getresponse()
            result_all = response.read().decode("utf-8")
            result = json.loads(result_all)
            # print(result)
            # print(result)

            trans_result = result['trans_result']
            for i in trans_result:
                # src=i['src']
                dst=i['dst']
                # data_list.append([src,dst])
                data_list.append(dst+'\n')  # 每行后面需要加上一个换行
            # src = trans_result[0]['dst']
            # src = '|'.join(dst_list)
            # print(src)
        except Exception as e:
            print(e)
        finally:
            if httpClient:
                httpClient.close()
        return data_list


    def clip_list(self,a,c):  #a为原列表，c为等分长度
        clip_back=[]
        if len(a)>c:
            for i in range(int(len(a) / c)):
                # print(i)
                clip_a = a[c * i:c * (i + 1)]
                clip_back.append(clip_a)
                # print(clip_a)
            # last 剩下的单独为一组
            last = a[int(len(a) / c) * c:]
            if last:
                clip_back.append(last)
        return clip_back


    def get_cliped_data(self):
        """
        获取切分好的列表
        """
        clip_count = 1
        pure_data = self._get_pure_data()
        if pure_data:
            keys = sorted(list(pure_data.keys()))
            vs = []  # 顺序语句列表
            number_list = []
            for i in keys:
                value = pure_data[i]
                vs.append(value)
                per_len = len(value)
                number_list.append(per_len)
            max_per_number = max(number_list)
            # print('max_per_number:',max_per_number)
            clip_count = 1950//max_per_number
            cliped_data = self.clip_list(vs,clip_count)

        return pure_data,cliped_data

    # def translate(self,data):
    #     """
    #     翻译内容
    #     """
    #     translated_list = []
    #     row = self.rows()
    #     row_list = [f'{i+1}\n' for i in range(row)]
    #     if data:
    #         for i in data:
    #             if i in row_list or '-->' in i:
    #                 translated_list.append(i)
    #             else:
    #                 tra_i = self.__translate(i)




